import { HttpException, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities//user.entity'
import { Repository } from 'typeorm'
import { JwtService } from '@nestjs/jwt';





@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private jwtService: JwtService
  ) { }

  async create(createUserDto: CreateUserDto) {
    const user = this.userRepository.create(createUserDto);
    await this.userRepository.save(user);
    return user;
  }

  async login(createUserDto: CreateUserDto) {
    const { username, password } = createUserDto; // , nickname, avatar
    const getuser = await this.userRepository.findOne({
      where: {
        username,
        // password,
        // nickname,
        // avatar,
      },
      select: ['id', 'username', 'password', 'nickname', 'avatar']
    })
    if (!getuser) {
      throw new HttpException('用户名或密码或者邮箱错误，请重新登录', 200)
    }
    return getuser


    /*
       if (!User || !(await User.checkPassword(password))) {
         throw new HttpException('用户名或密码错误', 401);
       }

       const payload = { username: User.username, sub: User.id };
       const access_token = this.jwtService.sign(payload);
       return { ...User, access_token };
   */
  }

  async findAll() {
    return await this.userRepository.find();
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
